function basePath(){
    var curWwwPath = window.document.location.href;
    var pathName =  window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0,pos);
    var projectName = pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return (localhostPath + projectName);
}

loading();

var page = 1;
var page_item_num = 0;
var item_num = 10;
var max_page_num = 0;

$(function () {
    getTeachers(page);
    validatorU();
    validatorA();
    $("#add_teacher_btn").click(function () {
        addTeacher();
    });
    $("#update_teacher_btn").click(function () {
        updateTeacher();
    });


});

function validatorU() {
    $('#updateForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            newTeacherName: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '教师用户名不能为空'
                    },
                    stringLength: {
                        min: 4,
                        max: 12,
                        message: '教师用户名在4位到12位之间'
                    },
                    different: {
                        field: 'name',
                        message: '教师用户名已存在，请重新输入'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '教师用户名只能由中文，数字和英文字母组成'
                    }
                }
            }
        }
    });
}

function validatorA() {
    $('#addForm').bootstrapValidator({
        message: 'is not valid',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            teacherName1: {
                message: 'this is not valid',
                validators: {
                    notEmpty: {
                        message: '教师用户名不能为空'
                    },
                    stringLength: {
                        min: 4,
                        max: 12,
                        message: '教师用户名在4位到12位之间'
                    },
                    different: {
                        field: 'name',
                        message: '教师用户名已存在，请重新输入'
                    },
                    regexp: {
                        regexp: /^(?=[0-9a-zA-Z\u4e00-\u9fa5]+$)/,
                        message: '教师用户名只能由中文，数字和英文字母组成'
                    }
                }
            }
        }
    });
}


function getTeachers(pageNum) {
    $.ajax({
        url: basePath()+'/edu/tea/all_teacher.do',
        type: 'GET',
        async: 'true',
        data: {
            "pageNum": pageNum,
            "pageSize": item_num
        },
        dataType: 'json',
        success: function (data) {
            removeLoading();

            var pageResult = data.data;
            var item = data.data.list;
            page_item_num = item.length;
            max_page_num = pageResult.pages;
            page = setPage(pageResult.pageNum, pageResult.pages, "getTeachers");
            $("#result").html("");
            for (var i = 0; i < item.length; i++) {
                var temp = $("#m_template").clone();
                temp.attr("id", item[i].id);
                temp.removeAttr("style");
                temp.find(".t_num").html(pageResult.pageSize * (pageResult.pageNum - 1) + 1 + i);
                temp.find(".t_name").html(item[i].name);
                temp.find(".t_className").html(item[i].className);
                //修改按钮组装
                var ucontent = "<button type='button'  class='btn btn-primary btn-xs btn-warning' style='margin-right: 10px;' onclick='toUpdate(" + item[i].id + ");' ><span class='glyphicon glyphicon-edit' aria-hidden='true'></span><span style='margin: 0px 8px;'>修改</span></button>"
                //删除按钮组装
                var dcontent = "<button type='button'  class='btn btn-primary btn-xs btn-danger' onclick='deleteTeacher(" + item[i].id + ");' ><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></span><span style='margin: 0px 8px;'>删除</span></button>"
                temp.find(".t_update").html(ucontent);
                temp.find(".t_operate").html(dcontent);
                //重置密码组装
                var resetBtn = "<button type='button' class='btn btn-primary btn-xs btn-danger' onclick='resetPassword(" + item[i].id + ")'><span class='glyphicon glyphicon-refresh' aria-hidden='true' style='padding-right: 3px;'></span><span style='margin: 0px 3px;'>重置密码</span></button>";
                temp.find(".t_reset").html(resetBtn);
                $("#result").append(temp);
            }
        }
    })
};

function resetPassword(id) {
    bootbox.confirm({
        message: "确认重置密码吗?",
        buttons: {
            confirm: {
                label: '<span class="glyphicon glyphicon-ok" aria-hidden="true"></span> 是',
                className: 'btn-danger'
            },
            cancel: {
                label: '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span> 否',
                className: 'btn-default'
            }
        },
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: basePath()+'/edu/tea/reset_pwd.do',
                    type: 'post',
                    data: {"id":id},
                    dataType: 'json',
                    success: function (res) {
                        if (res.success) {
                            bootbox.alert(res.msg);
                        } else {
                            bootbox.alert(res.msg);
                        }
                    }
                });
            }
        }
    });

}

function deleteTeacher(teacherId) {
    bootbox.setDefaults("locale", 'zh_CN');
    bootbox.confirm('确认要删除选择的数据吗?', function (res) {
        if (res) {
            var url = basePath()+"/edu/tea/delete_teacher.do";
            var data = {"teacherId": teacherId};
            $.get(url, data, function (data) {
                if (data.status == 0) {
                    bootbox.alert("删除成功");
                    if (page_item_num == '1') {
                        getTeachers(page - 1);
                    } else {
                        getTeachers(page);
                    }

                } else {
                    bootbox.alert(data.msg);
                }
            }, "JSON");
        }
    })

};

function toUpdate(teacherId) {
    var url = basePath()+"/edu/tea/toupdate_teacher.do";
    var data = {"teacherId": teacherId};
    $.get(url, data, function (data) {
        if (data.status == 0) {
            $("#newTeacherName").val(data.data.name);
            $("#newTeacherNameId").val(teacherId);
            $("#changTeacher").modal("show");
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");

}

function updateTeacher() {
    // 提交前先主动验证表单
    var bv = $("#updateForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    var url = basePath()+"/edu/tea/update_teacher.do";
    var name = $("#newTeacherName").val();
    var id = $("#newTeacherNameId").val();
    var data = {"id": id, "name": name};
    $.post(url, data, function (data) {
        if (data.status == 0) {
            $("#changTeacher").modal("hide");
            getTeachers(page);
            bootbox.alert(data.msg);
        } else {
            bootbox.alert(data.msg);
        }
    }, "JSON");
};

function addTeacher() {


    // 提交前先主动验证表单
    var bv = $("#addForm").data('bootstrapValidator');
    bv.validate();
    if (!bv.isValid()) {
        return;
    }

    var teachername = $("#teacherName1").val();
    $("#teacherName1").val("");

    $.ajax({
        url: basePath()+"/edu/tea/add_teacher.do",
        type: "post",
        async: "true",
        data: {"name": teachername},
        dataType: "json",
        success: function (data) {
            if (data.status == 0) {
                clearAddModel();
                bootbox.alert("添加成功");
                if (page_item_num == item_num) {
                    getTeachers(max_page_num);
                } else {
                    getTeachers(page);
                }
            }
            else {
                $('#addForm').data('bootstrapValidator').updateStatus('teacherName1', 'INVALID', 'different')
            }
        }
    });

}

function clearUpdateModel() {
    $('#changTeacher').modal('hide');
    $('#newTeacherName').val("");

    $('#updateForm').data('bootstrapValidator').destroy();
    $('#updateForm').data('bootstrapValidator', null);
    $("form[id='updateForm'] > div").addClass('has-success');
    validatorU();
}

function clearAddModel() {
    $('#addTeacher').modal('hide');
    $('#teacherName1').val("");

    $('#addForm').data('bootstrapValidator').destroy();
    $('#addForm').data('bootstrapValidator', null);
    $("form[id='addForm'] > div").addClass('has-success');
    validatorA();
}